package org.fastsyncer.connector.webservice;

import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.WebServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class WebServiceConnector implements WebService {

    private static final Logger LOG = LoggerFactory.getLogger(WebServiceConnector.class);

    private static volatile WebServiceConnector instance = null;

    private WebServiceConnector(){
    }
    
    public static WebServiceConnector getInstance() {
        if (null == instance) {
            synchronized (WebServiceConnector.class) {
                if (null == instance) {
                    instance = new WebServiceConnector();
                }
            }
        }
        return instance;
    }

    @Override
    public Object send(String url, String method, String msg) throws Exception {
        // 1.获取一个工厂实例
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();

        // 2.生成针对指定服务接口URL的客户端
        Client client = factory.createClient(url);

        // 3.调用指定的方法，注意入参第一个为方法名称，第二个为方法的参数（可以传入一个参数列表，一般为数组）
        Object[] objs = client.invoke(method, msg);

        // 4.关闭客户端连接
        client.destroy();

        // 5.返回响应结果
        return objs[0].toString();
    }

    @Override
    public boolean isAlive(Object config) {
        WebServiceConfig cfg = (WebServiceConfig) config;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(cfg.getUrl()).openConnection();
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                connection.disconnect();
                return true;
            }
        } catch (Exception e) {
            LOG.error("Failed to connect:" + cfg.getUrl(), e.getMessage());
        }
        return false;
    }

    @Override
    public BaseInfo getBaseInfoConnector(Object config) {
        WebServiceConfig cfg = (WebServiceConfig) config;
        return this.isAlive(cfg) ? new BaseInfo() : null;
    }

}
